import dayjs from "dayjs";
import editForm from "../form.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import userAvatar from "@/assets/header.png";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import {
  getKeyList,
  isAllEmpty,
  hideTextAtIndex,
  deviceDetection
} from "@pureadmin/utils";
import {
  department_list,
  position_list,
  role_list,
  user_list,
  user_add,
  user_save,
  user_del
} from "@/api/user"
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  reactive,
  onMounted,
  computed
} from "vue";

import { useUserStoreHook } from "@/store/modules/user";

export function useUser(tableRef: Ref, treeRef: Ref) {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_member_add: false, // 成员添加

    is_member_edit: false, // 修改
    is_member_resetPassword: false, // 修改密码
    is_member_del: false, // 删除
  })

  const form = reactive({
    // 左侧部门树的id
    department_belong: "",
    key: "",
    status: "",
    page: 1,
    pagesize: 10
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const deptData = ref([]);
  const deptLoading = ref(true);
  const positionData = ref([]);
  const roleData = ref([])

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns = reactive<TableColumnList>([
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "id",
      prop: "id",
      minWidth: 90
    },
    {
      label: "用户名称",
      prop: "account",
      minWidth: 130
    },
    {
      label: "昵称",
      prop: "nickname",
      minWidth: 100
    },
    {
      label: "所属部门",
      prop: "department_belong_name",
      minWidth: 120
    },
    {
      label: "职位",
      prop: "position_name",
      minWidth: 120
    },
    {
      label: "角色",
      prop: "role_name",
      minWidth: 120
    },
    {
      label: "启用状态",
      prop: "status",
      minWidth: 120,
      cellRenderer: ({ row, index }) => (
        <>
          {row.status === "1" ? "启用" : "停用"}
        </>
      )
    },
    {
      label: "电话号码",
      prop: "phone",
      minWidth: 120,
      formatter: ({ phone }) => hideTextAtIndex(phone, { start: 3, end: 6 })
    },
    {
      label: "创建时间",
      prop: "created_at",
      formatter: ({ created_at }) => dayjs.unix(created_at).format("YYYY-MM-DD HH:mm:ss"),
      minWidth: 180,
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 120
    }
  ]);

  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();

  function handleCommand(row, e) {
    console.log(row);
    if (e == "edit") openDialog('编辑', row);
    else if (e == "reset") handleReset(row)
    else if (e == "delete") handleDelete(row);
  }

  // 删除操作
  function handleDelete(row) {
    ElMessageBox.confirm("确定删除该用户", "重要提示", {
      type: "warning"
    }).then(() => {
      user_del({
        id: row.id
      }).then(res => {
        if (res.code == 1000) {
          message("删除成功", { type: "success" });
          onSearch(); // 刷新表格数据
        } else {
          message(res.msg, { type: "error" });
        }
      });
    }).catch(() => {});
  }

  function handleSizeChange(val: number) {
    form.pagesize = val;
    pagination.pageSize = val
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val
    onSearch(); // 刷新表格数据
  }

  async function onSearch() {
    loading.value = true;

    const result = await user_list(toRaw(form));

    dataList.value = result.data;
    pagination.total = result.count;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.department_belong = "";
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.department_belong = selected ? id : "";
    onSearch();
  }

  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          id: row?.id ?? "",
          higherDeptOptions: deptData.value,
          higherPositionOptions: positionData.value,
          higherRoleOptions: roleData.value,
          department_belong: row?.department_belong ?? null,
          position: row?.position ?? null,
          role: row?.role ?? null,
          nickname: row?.nickname ?? "",
          account: row?.account ?? "",
          password: row?.password ?? "",
          phone: row?.phone ?? "",
          status: row?.status ?? "1",
          is_root: row?.is_root ?? 0
        }
      },
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了用户名称为${curData.nickname}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            let curForm = JSON.parse(JSON.stringify(curData));
            delete curForm.higherDeptOptions
            delete curForm.higherPositionOptions
            delete curForm.higherRoleOptions
            if (!curForm.id) delete curForm.id;
            // 表单规则校验通过
            if (title === "新增") {
              user_add(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            } else {
              user_save(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            }
          }
        });
      }
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) => (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.nickname} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="my-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            ElMessageBox.confirm(`是否将此用户密码重置为 ${pwdForm.newPwd} ?`, "重要提示", {
              type: "warning"
            }).then(() => {
              user_save({
                id: row.id,
                department_belong: row.department_belong,
                position: row.position,
                role: row.role,
                nickname: row.nickname,
                account: row.account,
                password: pwdForm.newPwd,
                phone: row.phone,
                status: row.status,
                is_root: row.is_root
              }).then(res => {
                if (res.code == 1000) {
                  message(`已成功重置 ${row.nickname} 用户的密码`, { type: "success" });
                  done(); // 关闭弹框
                  onSearch(); // 刷新表格数据
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            }).catch(() => {});
          }
        });
      }
    });
  }

  onMounted(async () => {
    onSearch();

    // 获取部门列表
    onGetDepartmentList()
    // 获取职位列表
    onGetPositionList()
    // 获取角色列表
    onGetRoleList()

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/structureManagement/account/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/structureManagement/account/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // member_add
      if (homeDataObj.member_add) permissions.is_member_add = true
      // member_table
      if (homeDataObj.member_table) {
        // single
        if (homeDataObj.member_table.single && homeDataObj.member_table.single.length) {
          let permiss = homeDataObj.member_table.single.join(',')
          permissions.is_member_edit = permiss.includes('edit') ? true : false
          permissions.is_member_resetPassword = permiss.includes('resetPassword') ? true : false
          permissions.is_member_del = permiss.includes('del') ? true : false
        }

        let tableRemove = homeDataObj.member_table.remove ? homeDataObj.member_table.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  async function onGetDepartmentList() {
    deptLoading.value = true;
    const result = await department_list({ page: 1, pagesize: 999 });

    deptData.value = handleTree(result.data);
    deptLoading.value = false;
  }

  async function onGetPositionList() {
    const result = await position_list({ page: 1, pagesize: 999 });

    positionData.value = result.data;
  }

  async function onGetRoleList() {
    const result = await role_list({ page: 1, pagesize: 999 });

    roleData.value = result.data;
  }

  return {
    permissions,

    deptData,
    deptLoading,
    positionData,

    form,
    loading,
    columns,
    dataList,
    pagination,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    onTreeSelect,
    handleCommand,
    handleSizeChange,
    handleCurrentChange,
  };
}
